import { Injectable, Inject, HttpException, HttpStatus } from '@nestjs/common';
import { Response, ResponseParam } from '../../common/enums/response';
import { ApiErrorCode } from '../../common/enums/api-error-code.enum';
import { code2Session } from '../../common/wxapi/wx_sdk';
import { cosConfig } from '../../config/cos.config';
import * as STS from 'qcloud-cos-sts';
import { wxConfig } from 'src/config/weixin';
import { WxApi } from '../../common/wxapi/wxapi.service';
import { getRandomInt } from '../../util/utiles';
import { UserService } from '../user/user.service';
import { Auth } from '../../auth/auth';
import { User } from 'src/entities/user.entity';
const requestp = require('request-promise');

@Injectable()
export class WxService {
  constructor(
    private readonly wxApi: WxApi,
    private readonly userService: UserService,
  ) {}

  public async getStsAuto(): Promise<object> {
    // 获取临时密钥
    var policy = {
      version: '2.0',
      statement: [
        {
          action: [
            'cos:PostObject',
            'cos:PutObject*',
            'cos:InitiateMultipartUpload',
            'cos:UploadPart',
            'cos:CompleteMultipartUpload',
            'cos:AbortMultipartUpload',
          ],
          effect: 'allow',
          principal: { qcs: ['*'] },
          resource: '*',
        },
      ],
    };
    const _result: any = await this.getSTS(policy);
    const responseParam: ResponseParam = {
      message: ApiErrorCode.LACK_GET_SUCCESS,
      data: _result,
    };
    return Response(responseParam);
  }

  public async getclientUserOpenid(code: string, userId: number): Promise<any> {
    try {
      const openid: string = await code2Session(
        wxConfig.clientUser.appid,
        wxConfig.clientUser.secret,
        code,
      );
      const _openid: string = JSON.parse(openid).openid;
      const createdSe: number = await this.userService.pudOpenid(
        userId,
        _openid,
      );
      if (createdSe === 2) throw 'err';
      const responseParam: ResponseParam = {
        message: ApiErrorCode.LCAK_OPENID_SUCCESS,
        data: { openid: _openid },
      };
      return Response(responseParam);
    } catch (error) {
      throw new HttpException(
        ApiErrorCode.LCAK_OPENID_FAIL,
        HttpStatus.FORBIDDEN,
      );
    }
  }

  private getSTS(policy) {
    return new Promise((resolve, reject) => {
      STS.getCredential(
        {
          secretId: cosConfig.secretId,
          secretKey: cosConfig.secretKey,
          proxy: cosConfig.proxy,
          durationSeconds: cosConfig.durationSeconds,
          policy: policy,
        },
        function (err, tempKeys) {
          var result: any = JSON.stringify(err || tempKeys) || '';
          resolve(result);
        },
      );
    });
  }

  /**
   * @description: 用户端小程序退款
   * @param {string|number} out_trade_no 商户订单号
   * @param {string|number} out_refund_no 退款单号
   * @param {number} total_fee 订单金额
   * @param {number} refund_fee 退款金额
   * @param {string} refund_desc 退款原因
   * @return:
   */
  public async refundTest(
    out_trade_no: string,
    total_fee: number,
    refund_fee: number,
    refund_desc: string,
  ): Promise<any> {
    const out_refund_no = getRandomInt(1, 999999999);
    return this.wxApi.wxRefund(
      out_trade_no,
      out_refund_no,
      total_fee,
      refund_fee,
      refund_desc,
    );
  }

  public async geocoder(lat, lng) {
    let res: any;
    let requestData = {
      method: 'get',
      uri: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=D47BZ-VYVWQ-NNO5S-GLWIV-3USFJ-ZIBBN`,
      encoding: null,
      json: true,
    };
    //通过微信接口获取小程序码
    await requestp(requestData).then(function (body) {
      res = body;
    });
    return res;
  }

  /**
   * @description: 公众号网页授权获取openid
   * @param {string} code
   * @return:
   */
  public async getPublicOpenid(code: string) {
    return await this.wxApi.getPublicOpenid(code);
  }
}
